package com.wframe.project.jnd.controller;


import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wframe.framework.spring.SpringContextHolder;
import com.wframe.framework.util.UploadUtil;
import com.wframe.project.jnd.entity.FlashSalePromotion;
import com.wframe.project.jnd.entity.Promotion;
import com.wframe.project.jnd.rest.util.SessionUser;
import com.wframe.project.jnd.services.*;
import com.wframe.project.jnd.util.PromotionBuilderFactory;
import com.wframe.project.jnd.util.ServletUtils;
import com.wframe.project.jnd.util.TransformUtils;
import com.wframe.project.jnd.vo.CustomerAssistance;
import com.wframe.project.jnd.vo.CustomerItem;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.wframe.project.jnd.rest.util.JsonReturn;
import com.wframe.project.jnd.rest.util.WebSession;
import com.wframe.project.jnd.util.WebUtils;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductService productService;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    FloorService floorService;
    @Autowired
    private PromotionService promotionService;
    @Autowired
    InformationService informationService;
    private static final String ACTIVE_AREA_AD = "ACTIVE_AREA_AD";

    /**
     * 进入专题栏目
     *
     * @return
     */
    @RequestMapping(value = "subject")
    public String subject(String channelcode, HttpSession session, Model model) {
        String userid = "";
        if (WebSession.checkLoginStatus(session)) {
            userid = WebSession.getWbUser(session).getUserid();
        }
        model.addAttribute("channel", productService.querySubjectProduct(userid, channelcode).getDataMap());
        return "/website/products/subjectChannel";
    }

    /**
     * 商品列表页面
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "list")
    public String list(String clscode, String attritems, Integer ordertype, Integer orderby, Integer instock, String querylike, String floorid, String flooritemid, HttpServletRequest request, Model model) throws Exception {
        if (StringUtils.isBlank(clscode)) {
            clscode = "1";
        }
        clscode = TransformUtils.trans(clscode);
        floorid = TransformUtils.trans(floorid);
        flooritemid = TransformUtils.trans(flooritemid);

        String keyword = "";
        if (StringUtils.isNotBlank(querylike)) {
            querylike = querylike.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            keyword = URLDecoder.decode(querylike, "UTF-8");
        }
        model.addAttribute("subclslist", productService.getProductSubCls(clscode));
        String[] seleditems = null;
        if (StringUtils.isNotBlank(attritems)) {
            seleditems = attritems.split(",");
        }
        List<Map> attrlist = productService.getAttrs(clscode, seleditems);
        model.addAttribute("attrlist", attrlist);//属性列表
        model.addAttribute("showtype", StringUtils.isEmpty(request.getParameter("showtype")) ? "big" : request.getParameter("showtype"));
        model.addAttribute("clscode", clscode);
        model.addAttribute("clsnavs", productService.queryClsNav(clscode));//已选分类信息
        List<Map> attrNavs = null;
        if (seleditems != null) {
            attrNavs = productService.queryAttrNav(seleditems);//已选属性信息
        }
        if (StringUtils.isNotBlank(floorid) || StringUtils.isNotBlank(flooritemid)) {
            if (attrNavs == null) {
                attrNavs = new ArrayList<Map>();
            }
            if (StringUtils.isNotBlank(flooritemid)) {
                JdataBean flooritem = floorService.getFloorItem(flooritemid);
                if (flooritem != null) {
                    Map flooritemmap = new HashMap();
                    flooritemmap.put("attrname", "类目");
                    flooritemmap.put("text", flooritem.getString("name"));
                    flooritemmap.put("id", "flooritem_" + flooritemid);
                    attrNavs.add(0, flooritemmap);
                }
            }
            if (StringUtils.isNotBlank(floorid)) {
                JdataBean floor = floorService.getFloor(floorid);
                if (floor != null) {
                    Map floormap = new HashMap();
                    floormap.put("attrname", "楼层");
                    floormap.put("text", floor.getString("id") + "F");
                    floormap.put("id", "floor_" + floorid);
                    attrNavs.add(0, floormap);
                }
            }
        }
        int pageno = 1;
        if (StringUtils.isNotBlank(request.getParameter("pno"))) {
            pageno = Integer.parseInt(request.getParameter("pno"));
        }
        model.addAttribute("attrnavs", attrNavs);
        model.addAttribute("pageno", pageno);
        model.addAttribute("ordertype", ordertype);
        model.addAttribute("orderby", orderby);
        model.addAttribute("instock", instock);
        model.addAttribute("querylike", keyword);
        model.addAttribute("floorid", floorid);
        model.addAttribute("flooritemid", flooritemid);
        return "/website/products/list";
    }

    /**
     * 加载商品列表数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "loadproducts")
    public void loadproducts(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean parms = WebUtils.requestMapToBean(request.getParameterMap());
            int size = 20;
            int pageno = 1;
            if (StringUtils.isNotBlank(request.getParameter("pno"))) {
                pageno = Integer.parseInt(request.getParameter("pno"));
            }
            PageResult pr = null;

            if (WebSession.checkLoginStatus(request.getSession())) {
                parms.put("userId", WebSession.getWbUser(request.getSession()).getUserid());
                pr = productService.findWebProducts(parms, size, pageno, 1);
            } else {
                pr = productService.queryWebProduct(parms, size, pageno);
            }
            /*productService.queryPricegrade(userid, pr.getList());//价格等级
            if (parms != null && "3".equals(parms.getString("ordertype"))) {
                //价格重新排序（待优化）
                List<JdataBean> list = pr.getList();
                List<JdataBean> relist = new ArrayList<JdataBean>();
                for (JdataBean bean : list) {
                    boolean bl = false;
                    for (int a = 0; a < relist.size(); a++) {
                        if ("0".equals(parms.getString("ordertype"))) {
                            if (bean.getDouble("price") < relist.get(a).getDouble("pro")) {
                                bl = true;
                                relist.add(a, bean);
                                break;
                            }
                        } else {
                            if (bean.getDouble("price") > relist.get(a).getDouble("pro")) {
                                bl = true;
                                relist.add(a, bean);
                                break;
                            }
                        }

                    }
                    if (!bl) relist.add(bean);
                }
                pr.setList(relist);
            }*/
            JdataBean redata = new JdataBean();
            redata.put("products", pr.getList());
            redata.put("pagecount", pr.getPageCount());
            redata.put("resultcount", pr.getResultCount());
            redata.put("pagelist", WebUtils.toPageBean(pr, 7));
            json.putData(redata);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }

    }

    @RequestMapping(value = "offMsg")
    public String showOffProduct() {
        return "/website/products/offMsg";
    }

    /**
     * 商品详情
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "info")
    public String info(String priceid, String productid, HttpSession session, Model model) throws Exception {
        if (StringUtils.isBlank(priceid)) {
            List<Map> plist = productService.getProductPrices(productid);
            priceid = plist.get(0).get("id").toString();
        }
        Map product = productService.getProductInfo(priceid).getDataMap();
        if (!product.get("status").toString().equals("2")) {
            return "/website/products/offMsg";
        }

        SessionUser loginUser = WebSession.getWbUser(session);
        if (loginUser != null) {
            String userid = loginUser.getUserid();
            String productId = String.valueOf(product.get("id"));
            session.setAttribute("browsepriceid", productId);
            product.put("isfavorite", productService.checkfavorite(userid, productId));//是否收藏

            if (WebSession.checkWbUserAuth(userid)) {
                product.put("isControl", productService.isControlsales(userid, productId));//是否控销
                product.put("price", productService.findAppositePrice(userid, productId));//价格等级

                //商品促销信息
                Map<String, Promotion> promotionMap = new HashMap();
                Map<String, String> promotions = promotionService.findAll(productId, userid, Promotion.Platform.PC.ordinal());
                //单品促销
                String flashSale = Promotion.Type.FLASH_SALE.name();
                if (promotions.containsKey(flashSale)) {
                    FlashSalePromotion promotion = (FlashSalePromotion) PromotionBuilderFactory.get(flashSale).build(promotions.get(flashSale));
                    if (Objects.nonNull(promotion)) {
                        //单品促销有活动库存
                        promotionMap.put(flashSale.toLowerCase(), promotion);

                        //单品促销可用库存
                        int inventory = promotion.getAmount();
                        int amount = Integer.parseInt(String.valueOf(product.get("amount")));
                        product.put("amount", inventory > amount ? (amount > 0 ? amount : 0) : (inventory > 0 ? inventory : 0));
                    }
                    //单品促销无活动库存
                    promotions.remove(flashSale);
                }

                //其他促销
                Set<Map.Entry<String, String>> entries = promotions.entrySet();
                Iterator<Map.Entry<String, String>> iterator = entries.iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> next = iterator.next();
                    String promotionType = next.getKey();
                    String promotionId = next.getValue();
                    promotionMap.put(promotionType.toLowerCase(), PromotionBuilderFactory.get(promotionType).build(promotionId));
                }
                model.addAttribute("productPromotions", promotionMap);
            }
        }

        productService.addpopularity(priceid);

        model.addAttribute("bean", product);
        return "/website/products/info";
    }

    /**
     * 猜你喜欢
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "maylike")
    public void maylike(String priceid, Integer pagesize, Integer pageno, HttpSession session, HttpServletResponse
            response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            int size = 10;
            if (pagesize != null) {
                size = pagesize.intValue();
            }
            int pno = 1;
            if (pageno != null) {
                pno = pageno.intValue();
            }
            PageResult pr = productService.maylike(priceid, size, pno);
            String userid = "";
            if (WebSession.checkLoginStatus(session)) {
                userid = WebSession.getWbUser(session).getUserid();
                productService.queryPricegrade(userid, pr.getList());//价格等级
            }
            JdataBean data = new JdataBean();
            data.put("list", pr.getList());
            data.put("pcount", (pr.getPageCount() > 5 ? 5 : pr.getPageCount()));
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 热销商品
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "hots")
    public void hots(Integer pagesize, Integer pageno, HttpSession session, HttpServletResponse response, ModelMap
            model) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            int size = 10;
            if (pagesize != null) {
                size = pagesize.intValue();
            }
            int pno = 1;
            if (pageno != null) {
                pno = pageno.intValue();
            }
            PageResult pr = null;
            if (WebSession.checkLoginStatus(session)) {
                pr = productService.findHotProducts(WebSession.getWbUser(session).getUserid(), size, pno);
            } else {
                pr = productService.queryHotProducts(size, pno);
            }
//            productService.queryPricegrade(userid, pr.getList());//价格等级
            JdataBean data = new JdataBean();
            data.put("list", pr.getList());
            data.put("pcount", (pr.getPageCount() > 5 ? 5 : pr.getPageCount()));
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 收藏商品
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/favorite")
    public void addFavorite(String priceid, Integer action, HttpSession session, HttpServletResponse response) throws
            Exception {
        JsonReturn json = new JsonReturn();
        try {
            if (WebSession.checkLoginStatus(session)) {
                String userid = WebSession.getWbUser(session).getUserid();
                productService.favorite(userid, priceid, action);
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 收藏商品
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "delfavorites")
    public void delfavorites(String priceids, HttpSession session, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            if (WebSession.checkLoginStatus(session)) {
                String userid = WebSession.getWbUser(session).getUserid();
                if (StringUtils.isNotBlank(priceids)) {
                    String[] ids = priceids.split(",");
                    for (String id : ids) {
                        productService.favorite(userid, id, 1);
                    }
                }
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }


    /**
     * 商品收藏列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "favorites")
    public String queryFavorite(String pno, Model model, HttpSession session) throws Exception {
        if (!WebSession.checkLoginStatus(session)) {
            return "redirect:/user/showlogin";
        }
        int pagesize = 20;
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)) {
            pageno = Integer.parseInt(pno);
        }
        PageResult pr = productService.queryFavorite(WebSession.getWbUser(session).getUserid(), pagesize, pageno);
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        return "/website/user/favorite";
    }

    @RequestMapping(value = "collect")
    @ResponseBody
    public void querymyFavorite(String pno, HttpServletResponse response, HttpSession session) throws Exception {
        if (!WebSession.checkLoginStatus(session)) {
            response.sendRedirect("/user/showlogin");
        }
        int pagesize = 6;
        int pageno = 1;
        JsonReturn json = new JsonReturn();
        if (StringUtils.isNotBlank(pno)) {
            pageno = Integer.parseInt(pno);
        }
        PageResult pr = productService.queryFavorite(WebSession.getWbUser(session).getUserid(), pagesize, pageno);
        json.putData(pr);
        WebUtils.responseWrite(response, json.toString());

    }

    /**
     * 小能客服接口
     */
    @RequestMapping(value = "product", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public CustomerAssistance small(HttpServletRequest request, String productid, String userid) throws Exception {
        JdataBean productPrice = productService.getProductid(productid);
        CustomerItem items = new CustomerItem();
        CustomerAssistance assistance = new CustomerAssistance();
        items.setId(productPrice.getString("id"));
        items.setName(productPrice.getString("name"));


        items.setImageurl(UploadUtil.getConfig().getDownserver() + productPrice.getString("photo"));
        items.setUrl(ServletUtils.buildRequestUrlPrefix(request) + "/product/info?priceid=" + productPrice.getInt("id"));

        if (StringUtils.trimToNull(userid) != null) {
            items.setSiteprice(String.valueOf(productService.findAppositePrice(userid, productid)));
        }
        items.setCategory(productPrice.getString("category"));
        assistance.setItems(items);
        return assistance;
    }

    @RequestMapping("/activityArea")
    public String showActivityArea(Model model) {
        String result = null;
        JdataBean parm = new JdataBean();
        parm.put("code", "003005");
        try {
            StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
            if (stringRedisTemplate != null && stringRedisTemplate.opsForValue().get(ACTIVE_AREA_AD) != null) {
                String data = StringUtils.trimToEmpty(stringRedisTemplate.opsForValue().get(ACTIVE_AREA_AD));
                result = SerializationUtils.deserialize(Base64.decodeBase64(data));
            } else {
                List<Map<String, Object>> results = informationService.queryInfos(parm, 1, 1).getList();
                if (results.size() == 1) {
                    result = (String) results.get(0).get("phototitle");
                    String data = Base64.encodeBase64String(SerializationUtils.serialize(result));
                    stringRedisTemplate.opsForValue().set(ACTIVE_AREA_AD, data, 10, TimeUnit.MINUTES);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
//            List<Map<String,Object>> results = informationService.queryInfos(parm, 1, 1).getList();
        }
        model.addAttribute("active_ad", result);
        return "/website/products/active-area";
    }

    @RequestMapping("/promotions")
    @ResponseBody
    public String listActivityAreaProducts(HttpSession session, ModelMap map) {
        SessionUser sessionUser = WebSession.getWbUser(session);
        String userid = null;
        if (sessionUser != null) {
            userid = sessionUser.getUserid();
        }

        JsonReturn json = new JsonReturn();
        map.put(Promotion.Type.FLASH_SALE.name().toLowerCase(), promotionService.findOnSalePromotions(Promotion.Type.FLASH_SALE, Promotion.Platform.PC.ordinal(), Promotion.Weight.FLASH_SALE.ordinal(), 60 * 1000, TimeUnit.MILLISECONDS, userid));
        map.put(Promotion.Type.BUY_SEND.name().toLowerCase(), promotionService.findOnSalePromotions(Promotion.Type.BUY_SEND, Promotion.Platform.PC.ordinal(), Promotion.Weight.BUY_SEND.ordinal(), 1, TimeUnit.DAYS, userid));
        map.put(Promotion.Type.PURCHASE_GIFT.name().toLowerCase(), promotionService.findOnSalePromotions(Promotion.Type.PURCHASE_GIFT, Promotion.Platform.PC.ordinal(), Promotion.Weight.MONEY_OFF.ordinal(), 1, TimeUnit.DAYS, userid));
        json.putData(map);
        return json.toString();
    }

}
